#!/usr/bin/env python3
# refresh_vscode_tasks.py
import json, pathlib, sys, subprocess

BUILD_DIR   = pathlib.Path('build')
REPLY_DIR   = BUILD_DIR / '.cmake/api/v1/reply'
TASKS_FILE  = pathlib.Path('.vscode/tasks.json')

# ---------- 1. 若未配置，先配置 ----------
if not (BUILD_DIR / 'CMakeCache.txt').exists():
    print('检测到未配置，正在配置项目 …')
    subprocess.run(['cmake', '-S', '.', '-B', str(BUILD_DIR),
                    '-G', 'Ninja', '-DCMAKE_EXPORT_COMPILE_COMMANDS=ON'],
                   check=True)

# ---------- 2. 强制刷新 File API ----------
query_dir = BUILD_DIR / '.cmake/api/v1/query'
query_dir.mkdir(parents=True, exist_ok=True)
(query_dir / 'codemodel-v2').write_text('{}')
subprocess.run(['cmake', '-S', '.', '-B', str(BUILD_DIR)], check=True)

# ---------- 3. 找到 index 文件 ----------
index_files = list(REPLY_DIR.glob('index-*.json'))
if not index_files:
    sys.exit('找不到 index-*.json，确认 CMake ≥ 3.14')
index = json.loads(index_files[0].read_text())

# ---------- 4. 找到 codemodel 文件 ----------
for obj in index['objects']:
    if obj.get('kind') == 'codemodelV2' or 'codemodel' in obj.get('kind', ''):
        codemodel = json.loads((REPLY_DIR / obj['jsonFile']).read_text())
        break
else:
    sys.exit('codemodel 对象未找到')

# ---------- 5. 收集 + 过滤目标 ----------
skip_suffix = ('_autogen', '_autogen_timestamp_deps', 'gmock', 'gtest')
targets = []
for conf in codemodel['configurations']:
    for tgt in conf['targets']:
        t = tgt['name']
        if not any(t.endswith(s) for s in skip_suffix):
            targets.append(t)

# ---------- 6. 生成 tasks.json ----------
tasks = [
    {
        "label": f"CMake: build {t}",
        "type": "shell",
        "command": "cmake",
        "args": ["--build", "${workspaceFolder}/build", "--target", t, "--config", "${input:cmakeBuildType}"],
        "group": {"kind": "build", "isDefault": False},
        "problemMatcher": ["$gcc"]
    }
    for t in targets
]

whole = {
    "version": "2.0.0",
    "tasks": tasks,
    "inputs": [
        {
            "id": "cmakeBuildType",
            "type": "pickString",
            "description": "选择构建配置",
            "options": ["Debug", "Release"],
            "default": "Debug"
        }
    ]
}

TASKS_FILE.parent.mkdir(exist_ok=True)
TASKS_FILE.write_text(json.dumps(whole, indent=4))
print(f'✅ 已生成 {len(tasks)} 个任务到 {TASKS_FILE}')
